package com.usian;

import com.usian.pojo.ApComment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.internal.matchers.And;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@SpringBootTest(classes = App.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class Demo {
    @Autowired
    private MongoTemplate mongoTemplate;
    //添加
    @Test
    public void saveTest(){
        for (int i = 0; i <20 ; i++) {
            ApComment apComment = new ApComment();
            apComment.setAuthorName("小王");
            apComment.setContent("上海是不错的城市");
            apComment.setLikes(i);
            mongoTemplate.save(apComment);
        }
    }
    //根据id查询
    @Test
    public void findOne(){
        ApComment apComment = mongoTemplate.findById("62df55c6c7acee3754340299", ApComment.class);
        System.out.println(apComment);
    }
    //查询所有
    @Test
    public void findAll(){
        List<ApComment> comments = mongoTemplate.findAll(ApComment.class);
        System.out.println(comments);
    }
    //条件查询
    @Test
    public void findQuery(){
        Query query = new Query();
        query.addCriteria(Criteria.where("authorName").is("小王").and("likes").lt(10)).limit(5).with(Sort.by(Sort.Direction.DESC,"likes"));
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);
        System.out.println(list);
    }
    //修改
    @Test
    public void update(){
        Query query = new Query();
        query.addCriteria(Criteria.where("authorName").is("小王").and("likes").is(0));
        Update update = new Update();
        update.set("authorName","小王八");
        mongoTemplate.updateFirst(query,update,ApComment.class);
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("likes").is(0));
        ApComment comment = mongoTemplate.findOne(query1, ApComment.class);
        System.out.println(comment);
    }
    //删除
    @Test
    public void delete(){
        Query query = new Query();
        query.addCriteria(Criteria.where("authorName").is("小王八"));
        mongoTemplate.remove(query,ApComment.class);
    }
}
